package com.cloudwise.isop.drools.module;

import com.cloudwise.isop.drools.utils.ConfigUtils;
import com.google.inject.name.Names;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValue;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.guice.datasource.druid.DruidDataSourceProvider;

import java.util.Map;
import java.util.Properties;
import java.util.Set;

@NoArgsConstructor
public class MybatisModule extends org.mybatis.guice.MyBatisModule {

	@SneakyThrows
	@Override
	protected void initialize() {
		Config config = ConfigUtils.getConfig();
		bindDataSourceProviderType(DruidDataSourceProvider.class);
		bindTransactionFactoryType(JdbcTransactionFactory.class);
		addMapperClasses("com.cloudwise.isop.drools.dao");
		bind(Config.class).toInstance(config);
		Names.bindProperties(binder(), buildDatabaseProperties(config.getConfig("database")));
		addInterceptorsClasses("com.cloudwise.isop");
	}

	private Properties buildDatabaseProperties(Config conf) {
		Properties myBatisProperties = new Properties();
		Set<Map.Entry<String, ConfigValue>> confSet = conf.entrySet();
		for (Map.Entry<String, ConfigValue> entry : confSet) {
			myBatisProperties.setProperty(entry.getKey(), conf.getString(entry.getKey()));
		}
		return myBatisProperties;
	}
}
